$(function () {
    toggleLoading(true);
    var getParams = getArgs();
    var currentHotel = getParams.hotel;
    var orderNumber = getParams.no;
    var UserId = getParams.UserId;
    var originalHref = $('#doc-header a').attr('data-href');
    $('#doc-header a').attr('href', originalHref + '?hotel=' + currentHotel);
    originalHref = $('#doc-content a').attr('href');
    $('#doc-content a').attr('href', originalHref + '?hotel=' + currentHotel);
    var originalHref = $('.shareSubmit').data('href');
    $('.shareSubmit').attr('href', originalHref + '?hotel=' + currentHotel+'&no='+orderNumber+'&UserId='+UserId);
    
    toggleLoading(false);

    toastr.options = {
        "newestOnTop": false,
        "timeOut": 1500,
        "extendedTimeOut": 0,
        "escapeHtml": true,
        "positionClass": "toast-bottom-center"
    };
    if (currentHotel === undefined || currentHotel === '') {
        toastr.error(lang('toastr.grogshop'));
        return;
    }

    if (orderNumber === undefined || orderNumber === '') {
        toastr.error(lang('toastr.roomCard'));
        return;
    }
    if (UserId === undefined || UserId === '') {
        toastr.error(lang('toastr.roomCard'));
        return;
    }
    var hex2bin = function (hex) {
        var bytes = [],
            qrcodeResult = '';
        for (var i = 0; i < hex.length - 1; i += 2) {
            bytes.push(parseInt(hex.substr(i, 2), 16));
        }
        qrcodeResult = String.fromCharCode.apply(String, bytes);
        return qrcodeResult;
    };

    var qrSuccess = function (data) {
        var codeInfo = data.data;
        $('.look-for-help').removeClass('hidden');
        $('#doc-header .navbar-title').html(codeInfo.hotelName);
        $('#qrcode-room .info').html(codeInfo.roomTypeName +' - '+codeInfo.roomName);
        $('#qrcode-room .shareSubmit').removeClass('hidden');
        $('#qrcode-room').removeClass('room-style');
        var qrcodeResult = hex2bin(codeInfo.cardString);
        window.qrcode.html('');
        window.qrcode.qrcode({
            width: 164,
            height: 164,
            text: qrcodeResult
        });
        var currTime = new Date().getTime();
        var loading_time = currTime - window.start_loading_time;
        var waiting_loading_time;
        if (loading_time > 800) {
            waiting_loading_time = 0;
        } else {
            waiting_loading_time = 800 - loading_time;
        }
        window.setTimeout(function () {
            $('#loading-img').addClass('hidden');
            $('#broken-img').addClass('hidden');
            $('#qrcode-img,#qrcode-img-logo').removeClass('hidden');
            $('#img-success')['0'].pause();
            $('#img-success')['0'].play();
        }, waiting_loading_time);
    };
    var qrError = function (error) {
        if(error.responseJSON.data = '403602'){
            $('.contact-the-shopkeeper').removeClass('hidden').attr('href','tel:'+error.responseJSON.telephone);
        }else{
            $('.contact-the-shopkeeper').addClass('hidden');
            $('.look-for-help').removeClass('hidden');
        }
        toastr.error(typeof error.responseJSON === 'undefined' ? lang('tip.system') : error.responseJSON.info);
        var currTime = new Date().getTime();
        var loading_time = currTime - window.start_loading_time;
        var waiting_loading_time;
        if (loading_time > 800) {
            waiting_loading_time = 0;
        } else {
            waiting_loading_time = 800 - loading_time;
        }
        $('#qrcode-room').addClass('room-style');
        $('#qrcode-room .shareSubmit').addClass('hidden');
        window.setTimeout(function () {
            $('#loading-img').addClass('hidden');
            $('#qrcode-img,#qrcode-img-logo').addClass('hidden');
            $('#broken-img').removeClass('hidden');
            if(parseInt(error.responseText.slice(9,15)) == 403606){
                $('#noQrcard-img').removeClass('hidden');
                $('#broken-img').addClass('hidden');
                $('#doc-body .help-open').addClass('hidden');
                $('#doc-body .text-info .padding-horizon').text(lang('nonsupportQR'));
            }   
        }, waiting_loading_time);
    };

    var requestQRCode = function () {
        if ($('#loading-img').hasClass('hidden')) {
            window.start_loading_time = new Date().getTime();
            $('#loading-img').removeClass('hidden');
            $('#broken-img').addClass('hidden');
            $('#qrcode-img,#qrcode-img-logo').addClass('hidden');
            ajaxRequest('/Home/Card/detail', {
                'hotel': currentHotel,
                'bookUserId': UserId,
                'orderRoomId': orderNumber
            }, 'POST', qrSuccess, qrError);
        }
    };

    var deviceMotionHandler = function (eventData) {
        var acceleration = eventData.accelerationIncludingGravity;
        var curTime = new Date().getTime();
        if (curTime - window.last_update > 100) {
            var diffTime = curTime - window.last_update;
            window.last_update = curTime;
            window.origin_x = acceleration.x;
            window.origin_y = acceleration.y;
            window.origin_z = acceleration.z;
            var speed = Math.abs(window.origin_x + window.origin_y + window.origin_z - window.last_x - window.last_y - window.last_z) / diffTime * 10000;
            if (speed > window.SHAKE_THRESHOLD) {
                requestQRCode();
            }
            window.last_x = window.origin_x;
            window.last_y = window.origin_y;
            window.last_z = window.origin_z;
        }
    };
    window.SHAKE_THRESHOLD = 3000;
    window.last_update = 0;
    window.origin_x = 0;
    window.origin_y = 0;
    window.origin_z = 0;
    window.last_x = 0;
    window.last_y = 0;
    window.last_z = 0;
    window.qrcode = $('#qrcode-img');
    if (window.DeviceMotionEvent) {
        window.addEventListener('devicemotion', deviceMotionHandler, false);
    } else {
        toastr.warnning(lang('sorry'));
    }
    // 点击二维码刷新
    window.start_loading_time = 0;
    $('#qrcode-img').on('click', function (e) {
        e.preventDefault();
        requestQRCode();
    });

    $('#broken-img').on('click', function (e) {
        e.preventDefault();
        requestQRCode();
    });

    requestQRCode();
    
    //分享  
    ajaxRequest('/Home/Order/getShareUserList', {
        'hotel' : currentHotel,
        'orderRoomId' : orderNumber
    }, 'post', function (data) {
        var shareHTML = '';
        $.each(data.data, function (key, shareInfo) {
            var templateshareHTML = $($('#templateShareList').clone().html());
            templateshareHTML.find('.share-name').text(shareInfo.name);
            templateshareHTML.find('.share-mobile').text('+'+shareInfo.areacode +' '+ shareInfo.mobile).attr('data-id',shareInfo.id);
            templateshareHTML.find('.share-delete').attr('data-id',shareInfo.id);
            if(shareInfo.identity != ''){
                templateshareHTML.find('.share-bottom').removeClass('hidden').find('.share-identity').text(shareInfo.identity);
            }
            shareHTML += templateshareHTML.prop('outerHTML');
        });
        $('#shareContainer').html(shareHTML);     
        //滑动事件
        var lines = $("#shareContainer .move-content");
        var len = lines.length,lastX, lastXForMobile,pressedObj,lastLeftObj,start;
        if(goPAGE()){
            //移动端
            for (var i = 0; i < len; i++) {
                lines[i].addEventListener('touchstart', function(e){
                    lastXForMobile = e.changedTouches[0].pageX;
                    pressedObj = this.children[0];
                    var touches = e.touches[0];
                    start = { 
                        x: touches.pageX,
                        y: touches.pageY 
                    };
                });
                lines[i].addEventListener('touchmove',function(e){
                    var touches = e.touches[0];
                    delta = {
                        x: touches.pageX - start.x,
                        y: touches.pageY - start.y
                    };
                    if (Math.abs(delta.x) > Math.abs(delta.y)) {
                        event.preventDefault();
                    }
                });
                lines[i].addEventListener('touchend', function(e){
                    if (lastLeftObj && pressedObj != lastLeftObj) { 
                        $(lastLeftObj).animate({left:"0"}, 100);
                        lastLeftObj = null;
                    }
                    var diffX = e.changedTouches[0].pageX - lastXForMobile;
                    if (diffX < -50) {
                        $(pressedObj).animate({left:"-110px"}, 100);
                        lastLeftObj && lastLeftObj != pressedObj && 
                            $(lastLeftObj).animate({left:"0"}, 100);
                        lastLeftObj = pressedObj;
                    } else if (diffX > 50) {
                      if (pressedObj == lastLeftObj) {
                        $(pressedObj).animate({left:"0"}, 100);
                        lastLeftObj = null;
                      }
                    }
                });
            }               
        }else{
            //PC端
            for (var i = 0; i < len; i++) {
                $(lines[i]).bind('mousedown', function(e){
                    e.preventDefault();
                    lastX = e.clientX;
                    pressedObj = this.children[0];
                });
                $(lines[i]).bind('mouseup', function(e){
                    e.preventDefault();
                    if (lastLeftObj && pressedObj != lastLeftObj) {
                        $(lastLeftObj).animate({left:"0"}, 100);
                        lastLeftObj = null;
                    }
                    var diffX = e.clientX - lastX;
                    if (diffX < -20) {
                        $(pressedObj).animate({left:"-110px"}, 100);
                        lastLeftObj && lastLeftObj != pressedObj && 
                        $(lastLeftObj).animate({left:"0"}, 100);
                        lastLeftObj = pressedObj;
                    } else if (diffX > 20) {
                        if (pressedObj == lastLeftObj) {
                            $(pressedObj).animate({left:"0"}, 100);
                            lastLeftObj = null;
                        }
                    }
                });
            }  
        }               
    }, function(error){
        toastr.error(typeof error.responseJSON === 'undefined' ? lang('tip.server') : error.responseJSON.info);
    });    
    $('#shareContainer').on('click','.share-delete',function(e){
        e.stopPropagation();
        var submitBtn = $(this);
        ajaxRequest('/Home/Order/deleteShareUser', {
            'orderUserId' : submitBtn.data('id')
        }, 'post', function (data) {
            submitBtn.closest('.share-list-parent').remove();
        }, function(error){
            toastr.error(typeof error.responseJSON === 'undefined' ? lang('tip.server') : error.responseJSON.info);
        });           
    });    
    var isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    $('#shareContainer').on('click','.share-mobile',function(e){
        e.stopPropagation();
        var orderUserId = $(this).data('id');
        if(!goPAGE()){
            toastr.error(lang('lock.tip'));
        }else{
            ajaxRequest('/Home/Order/getCardLink', {
                'hotelId': currentHotel,
                'orderRoomId' : orderNumber,
                'orderUserId' : orderUserId
            }, 'post', function (data) {
                var info = data.data;
                if(isiOS){
                    $('#textLabels').attr('href','sms:+'+info.areaCode +' '+info.mobile+'&body='+info.link);
                }else{
                    $('#textLabels').attr('href','sms:+'+info.areaCode +' '+info.mobile+'?body='+info.link);
                }
                document.getElementById("textLabels").click();
            }, function(error){
                toastr.error(typeof error.responseJSON === 'undefined' ? lang('tip.server') : error.responseJSON.info);
            });             
        }        
    });
    function goPAGE() {
        if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
            return true;
        }else {
            return false;
        }
    }    
});
